var BASE =BASE||{};
BASE.UPLOAD = (function () {
    var ue = null;
    /*初始化编辑器*/
    if ($('#editorContent').length>0){
        var E = window.wangEditor;
        ue = new E('#editorContent');
        ue.customConfig.uploadImgShowBase64 = true;
        ue.create();
        E.extend.init('#editorContent');
        initEditor();
       /* /!*图片上传*!/
        ue.customConfig.customUploadImg = function (files, insert) {
            console.log(files);
            console.log(insert);
            for (var i = 0; i < files.length; i++) {
                var obj = files[i];
                uploadImage(obj,function (imgUrl) {
                    insert(imgUrl);
                })
            }
        };*/
    }else {
        ue = null;
    }
    /*编辑器禁用状态*/
    function initEditor() {
        var userId = BASE.COMMON.getUserId();
        if(userId){
            ue.$textElem.attr('contenteditable', true);
        }else {
            ue.$textElem.attr('contenteditable', false);
        }
    }
    
    /*图片上传*/
    function uploadImage(obj,callback) {
        var formData = new FormData();
        var image = '';
        var reader = new FileReader();
        reader.onload = function(e){
            image = e.target.result;
            var bob = getBob(image);
            var imageFile = new File([bob],'1.png',{type:"image/jpeg"});
            formData.append("imageFile",imageFile);
            //头像header,身份证idcard,video视频相关,course课程相关,question问题相关,training作业,bbs相关)
            formData.append('code',$('#box').data('uptype') || $('#middle').data('uptype'));
            upLoadImg(formData,function (url) {
                if(callback && typeof callback=="function"){
                    callback(url);
                }
            })
        };
        reader.readAsDataURL(obj);
    }
    /*文件上传*/
    function uploadFile(obj) {
        var fileName =obj.files[0].name;
        var formData = new FormData();
        var file = '';
        var reader = new FileReader();
        reader.onload = function(e){
            file = e.target.result;
            var bob = getBob(file);
            var imageFile = new File([bob],fileName,{type:"*/*"});
            formData.append("file",imageFile);
            //头像header,身份证idcard,video视频相关,course课程相关,question问题相关,training作业,bbs相关)
            formData.append('code',$('#box').data('uptype'));
            _upfile(formData,function (url) {
               $('#uploadFile').data('url',url).fadeIn().find('span').html('已上传附件：'+fileName);
                $('.editor-add-file').hide();
            })
        };
        reader.readAsDataURL(obj.files[0]);
    }
    /* 文件上传服务器*/
    function _upfile(formData,callback) {
        $.ajax({
            type: 'post',
            url: BASE.baseUrlLocal + '/device/upload/uploadFile',
            data: formData,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            dataType: "json",
            processData: false,
            contentType: false,
            beforeSend:function (request) {
                var token = BASE.getStore('userToken');
                if (token) {
                    request.setRequestHeader("token", token);
                }
                BASE.loadingTips(true,'正在上传')
            },
            success:function (res) {
                BASE.loadingTips(false);
                if (res.code!=200){
                    BASE.loadingTips(true,res.message,'wrong');
                    setTimeout(function () {
                        BASE.loadingTips(false);
                    },5000);
                    return;
                }
                if(callback && typeof callback == 'function'){
                    callback(res.data);
                }
            }
        });
    }
   /* 图片上传服务器*/
    function upLoadImg(formData,callback) {
        $.ajax({
            type: 'post',
            url: BASE.baseUrlLocal + '/device/upload/uploadImage',
            data: formData,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            dataType: "json",
            processData: false,
            contentType: false,
            beforeSend:function (request) {
                var token = BASE.getStore('userToken');
                if (token) {
                    request.setRequestHeader("token", token);
                }
                BASE.loadingTips(true,'正在上传')
            },
            success:function (res) {
                BASE.loadingTips(false);
                if(res.code!=200){
                    BASE.loadingTips(true,res.message,'wrong');
                    setTimeout(function () {
                        BASE.loadingTips(false);
                    },5000);
                    return;
                }
                if(callback && typeof callback == 'function'){
                    callback(res.data);
                }
            }
        });
    }
    /*获取图片的二进制文件*/
    function getBob(data) {
        var b64 =data.split('base64,').pop();
        var binary = atob(b64);
        var array = [];
        for (var i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return  new Blob([new Uint8Array(array)]);
    }
    /*删除附件*/
    function deleFile(obj) {
        $(obj).parents('#uploadFile').fadeOut().data('url','');
        $('.editor-add-file').fadeIn();
    }
    return {
        ue:ue,
        uploadImage:uploadImage,
        uploadFile:uploadFile,
        deleFile:deleFile,
        upLoadImg:upLoadImg,
        getBob:getBob,
    }
})();
